<?php


namespace app\common\service;


use app\common\controller\RegisteredPhone;
use app\common\model\Error;
use app\login\model\Registered;
use Exception;
use think\Db;
use app\common\model\Registered as RegisteredModel;

class getPhoneInfoService
{

    public function getRegisteredData($page,$limit, $name)
    {
        $model = new Registered();
        $result = $model->where('from','=',$name)
            ->order(['add_time' => 'desc']);
        $count = $result->count();
        $data = $result->page($page,$limit)
            ->select();
        return [
            'count' => $count,
            'data' => $data,
            'code' => 0
        ];
    }

    public function checkHasPhone($result_arr)
    {
        $user_model = $result_arr['user'];
        if($result_arr['type'] == 'f'){
            $data = $user_model->getPhoneMoneyDataF($result_arr['phone_arr'], $result_arr['logo'])
                ->toArray();
        }
        if($result_arr['type'] == 'd'){
            $data = $user_model->getPhoneMoneyDataD($result_arr['phone_arr'], $result_arr['logo'])
                ->toArray();
        }
        return $data;
    }

    /**
     * 根据所有手机号码获取贷款金额和放款金额
     * @param $arr 手机号码数组
     */
    public function getPhoneMoneyDate($result_arr)
    {
        $user_model = $result_arr['user'];
        if($result_arr['type'] == 'f'){
            $data = $this->getMoneyF($result_arr['phone_arr'], $user_model, $result_arr['logo']);
        }
        if($result_arr['type'] == 'd'){
            $data = $this->getMoneyD($result_arr['phone_arr'], $user_model, $result_arr['logo']);
        }
        return $data;
    }
    # 拼装单期的数组
    private function getMoneyD($arr, $user_model, $logo)
    {
        $data = $user_model->getPhoneMoneyDataD($arr, $logo)
            ->toArray();

        $phone_value = null;
        if(empty($data)){
            $null = [
                'phone' => $arr[0],
                'user_loan_d' => [
                    'money' => 20,
                    'loan_day' => 20,
                    'get_money' => 20,
                    'status' => 20
                ]
            ];
            $data[0] = $null;
        }else{
            foreach ($data as $key=>$value){
                $phone = $value['phone'];
                if($value['user_loan_d'] == null){
                    $value['user_loan_d']['money'] = 21;
                    $value['user_loan_d']['loan_day'] = 21;
                    $value['user_loan_d']['get_money'] = 21;
                    $value['user_loan_d']['status'] = 21;
                    $data[$key]['user_loan_d'] = $value['user_loan_d'];
                }else{
                    # 直接把status写入数据库
//                    $status_data = $this->getStatusD($value['user_loan_d']['status']);
//                    unset($data[$key]['user_loan_d']['status']);
//                    $data[$key]['user_loan_d']['status'] = $status_data;
                }
                $phone_key = array_search($phone,$arr);
                unset($arr[$phone_key]);
            }
            # 添加没有查询出来的手机号码的信息
            # 因为连表查询的结果直接有数据的手机号码才会显示
            # 因为每次count()的值都在加1
            foreach ($arr as $key=>$value ){
                $count_arr = count($data);
                $null = [
                    'id'=> null,
                    'phone' => $value,
                    'user_loan_d' => [
                        'money' => 20,
                        'loan_day' => 20,
                        'get_money' => 20,
                        'status' => 20
                    ]
                ];
                $data[$count_arr] = $null;
            }
        }

        return $data;
    }
    # 拼装分期的数组
    private function getMoneyF($arr, $user_model, $logo)
    {
        $data = $user_model->getPhoneMoneyDataF($arr, $logo)
            ->toArray();

        $phone_value = null;
        if(empty($data)){
            $null = [
                'phone' => $arr[0],
                'user_loan_f' => [
                    'money' => 20,
                    'get_money' => 20,
                    'periods' => 20,
                    'status' => 20
                ]
            ];
            $data[0] = $null;
        }else{
            foreach ($data as $key=>$value){
                $phone = $value['phone'];
                if($value['user_loan_f'] == null){
                    $value['user_loan_f']['money'] = 21;
                    $value['user_loan_f']['get_money'] = 21;
                    $value['user_loan_f']['periods'] = 21;
                    $value['user_loan_f']['status'] = 21;
                    $data[$key]['user_loan_f'] = $value['user_loan_f'];
                }else{
                    # 直接把status写入数据库
//                    $status_data = $this->getStatusF($value['user_loan_f']['status']);
//                    unset($data[$key]['user_loan_f']['status']);
//                    $data[$key]['user_loan_f']['status'] = $status_data;
                }
                $phone_key = array_search($phone,$arr);
                unset($arr[$phone_key]);
            }
            # 添加没有查询出来的手机号码的信息
            # 因为连表查询的结果直接有数据的手机号码才会显示
            # 因为每次count()的值都在加1
            foreach ($arr as $key=>$value ){
                $count_arr = count($data);
                $null = [
                    'id'=> null,
                    'phone' => $value,
                    'user_loan_f' => [
                        'money' => 20,
                        'get_money' => 20,
                        'periods' => 20,
                        'status' => 20
                    ]
                ];
                $data[$count_arr] = $null;
            }
        }

        return $data;
    }
    # 根据status获取当前status对应的值（单期）
    private function getStatusD($status)
    {
        $d_status_arr = config('status.d');
        return $d_status_arr[$status];
    }
    # 根据status获取当前status对应的值（分期）
    private function getStatusF($status)
    {
        $f_status_arr = config('status.f');
        return $f_status_arr[$status];
    }

    # 根据结果输出html(单期)
    public function htmlD($result, $phone)
    {
        $user_loan_d_first = $result[0]['user_loan_d'];
        $status = $this->getStatusD($user_loan_d_first['status']);
        $user_loan_d = $this->getLoanStatus($user_loan_d_first, $status);
        Db::startTrans();
        try{
            $model = new Registered();
            $model->update_user_loan_d($phone, $user_loan_d);
            Db::commit();
        }catch (Exception $e){
            echo $e->getMessage();
            Db::rollback();
        }
        $html = "
            <table class='layui-table'>
                  <colgroup>
                    <col width='150'>
                    <col width='200'>
                    <col>
                  </colgroup>
                  <tbody>
                    <tr>
                      <td>手机号码</td>
                      <td>{$phone}</td>
                    </tr>
                    <tr>
                      <td>借款金额</td>
                      <td>{$user_loan_d['money']}</td>
                    </tr>
                    <tr>
                      <td>贷款时间</td>
                      <td>{$user_loan_d['loan_day']}</td>
                    </tr>
                    <tr>
                      <td>放款金额</td>
                      <td>{$user_loan_d['get_money']}</td>
                    </tr>
                    <tr>
                      <td>状态</td>
                      <td>$status</td>
                    </tr>
                  </tbody>
                </table>
        ";
        return [
            'data' => $user_loan_d,
            'html' => $html,
        ];
    }
    # 根据结果输出html(多期)
    public function htmlF($result, $phone)
    {
        $user_loan_f_first = $result[0]['user_loan_f'];
        $status = $this->getStatusF($user_loan_f_first['status']);
        $user_loan_f = $this->getLoanStatus($user_loan_f_first, $status);
        Db::startTrans();
        try{
            $model = new Registered();
            $model->update_user_loan_f($phone, $user_loan_f);
            Db::commit();
        }catch (Exception $e){
            echo $e->getMessage();
            Db::rollback();
        }
        $html = "
            <table class='layui-table'>
                  <colgroup>
                    <col width='150'>
                    <col width='200'>
                    <col>
                  </colgroup>
                  <tbody>
                    <tr>
                      <td>手机号码</td>
                      <td>{$phone}</td>
                    </tr>
                    <tr>
                      <td>借款金额</td>
                      <td>{$user_loan_f['money']}</td>
                    </tr>
                    <tr>
                      <td>贷款期数</td>
                      <td>{$user_loan_f['periods']}</td>
                    </tr>
                    <tr>
                      <td>放款金额</td>
                      <td>{$user_loan_f['get_money']}</td>
                    </tr>
                    <tr>
                      <td>状态</td>
                      <td>$status</td>
                    </tr>
                  </tbody>
                </table>
        ";
        return [
            'data' => $user_loan_f,
            'html' => $html,
        ];
    }

    # 更新每个手机号码的记录
    public function updatePhoneInfo($json)
    {
        try {
            $arr = json_decode($json, true);
            # 得到分类好的手机号码数组
            $data = $this->getTypePhone($arr);
            $result = $this->updatePhoneByType($data);
            return $result;
        }catch (\Exception $e){
            $data = [
                'error_data' => '更新出错',
            ];
            Error::addErrorLog($data, $e);
            return ['code' => 400];
        }
    }
    # 把json字符串转成数组，提取每个行数据的type和phone，组成一个新的数组
    private function getTypePhone($arr)
    {
        $infos = [];
        foreach ($arr as $key=>$value){
            $info = ['phone' => $value['phone'], 'type' => $value['type'], 'logo' => $value['logo']];
            array_push($infos, $info);
        }
        return $infos;
    }
    # 更新每一个手机号码的状态
    private function updatePhoneByType($data)
    {
        # 放回一个数组，数组有一个user模型对象
        $common = new RegisteredPhone();
        $model = new RegisteredModel();
        foreach ($data as $key => $value){
            if ($value['type'] == 'f'){
                # 获取手机号码查询出来的结果
                $result_arr = $common->getRegisteredPhoneMoney([$value['phone']], $value['type'], $value['logo']);
                $arr = $this->getMoneyF($result_arr['phone_arr'], $result_arr['user'], $result_arr['logo']);
                $arr_first = $arr[0];
                $user_arr = [
                    'user_loan_money' => $arr_first['user_loan_f']['money'],
                    'user_loan_get_money' => $arr_first['user_loan_f']['get_money'],
                    'user_periods' => $arr_first['user_loan_f']['periods'],
                    'loan_status' => $arr_first['user_loan_f']['status'],
                ];
                $model->updatePhoneInfo($arr_first['phone'], $value['type'], $user_arr);
            }
            if ($value['type'] == 'd'){
                # 获取手机号码查询出来的结果
                $result_arr = $common->getRegisteredPhoneMoney([$value['phone']], $value['type'], $value['logo']);
                $arr = $this->getMoneyD($result_arr['phone_arr'], $result_arr['user'], $value['logo']);
                $arr_first = $arr[0];
                $user_arr = [
                    'user_loan_money' => $arr_first['user_loan_d']['money'],
                    'user_loan_get_money' => $arr_first['user_loan_d']['get_money'],
                    'user_loan_day' => $arr_first['user_loan_d']['loan_day'],
                    'loan_status' => $arr_first['user_loan_d']['status'],
                ];
                $model->updatePhoneInfo($arr_first['phone'], $value['type'], $user_arr);
            }
        }
        return [
            'code' => 200
        ];
    }
    #
    private function getLoanStatus($status_arr, $msg)
    {
        if($status_arr['status'] == 20 || $status_arr['status'] == 21){
            foreach ($status_arr as $key => $value){
                if($key == 'status'){
                    continue;
                }
                $status_arr[$key] = $msg;
            }
        }
        return $status_arr;
    }
}